package com.zx._01_基础._012_反射;

import java.lang.reflect.Method;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class 获得当前方法名 {

    @Test
    public void test1() {
        StackTraceElement element = new Exception().getStackTrace()[0];
        log.info("getClassName={}", element.getClassName());
        log.info("getMethodName={}", element.getMethodName());
        log.info("getLineNumber={}", element.getLineNumber());
        log.info("getFileName={}", element.getFileName());
    }

    @Test
    public void test2() {
        StackTraceElement element = Thread.currentThread().getStackTrace()[1];
        log.info("getClassName={}", element.getClassName());
        log.info("getMethodName={}", element.getMethodName());
        log.info("getLineNumber={}", element.getLineNumber());
        log.info("getFileName={}", element.getFileName());
    }

    @Test
    public void test3() {
        // 必须创建一个匿名内部类的对象
        Method method = new Object() {
        }.getClass().getEnclosingMethod();
        log.info("getMethodName={}", method.getName());
    }

    @Test
    public void test4() {
        StackWalker walker = StackWalker.getInstance();
        Optional<String> optional = walker.walk(frames -> frames
                .findFirst()
                .map(StackWalker.StackFrame::getMethodName));
        log.info("getMethodName={}", optional.get());
    }
}
